package com.zbbz.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * @author WangYang
 * @date 2025/02/13/15:15
 */
@Component
public class TokenUtil {
    // 令牌自定义标识
    private String header = "ApiAuthorization";

    // 令牌秘钥
    private String secret = "abcde1fghijklmnopq2rst4vwxyz";

    // 令牌有效期（单位毫秒）
    private long expireTime = 20 * 365 * 24 * 60 * 60 * 1000L; // 20年

    public static ThreadLocal<Object> vrEmployeeThreadLocal = new ThreadLocal<>();

    /**
     * 获取用户身份信息
     */
    public Integer getUserId(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (token != null && !token.isEmpty()) {
            try {
                Claims claims = parseToken(token);

                Integer id = (Integer)claims.get("id");

                return id;
            } catch (Exception e) {
            }
        }
        return null;
    }


    /**
     * 从数据声明生成令牌
     */
    public String createGateToken(Long id) {

        // 把uuid放入jwt中
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", id);

        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(new Date().getTime() + expireTime))
                .signWith(SignatureAlgorithm.HS512, secret).compact();

        return token;
    }

    /**
     * 从令牌中获取数据声明 如果过期会报错
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (token != null && !token.isEmpty()) {
            return token;
        }
        return token;
    }
}